<template>
  <div class="app-container">
      <el-form ref="form" :model="queryParams" :inline="true" label-width="80px">
        <el-form-item label="物品名称:">
          <el-input
            v-model="queryParams.articleName"
            clearable
            size="small"
            style="width: 240px"
          ></el-input>
        </el-form-item>

        <el-form-item label="损坏日期:">
          <el-date-picker 
            style="width: 100%"
            size="small"
            v-model="queryParams.damageTime"
            value-format="yyyy-MM-dd"
            type="date"
            clearable
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="维修状态:">
          <el-select v-model="queryParams.applyStatus" size="small">
            <el-option value="1" label="待审批"></el-option>
            <el-option value="2" label="审批驳回"></el-option>
            <el-option value="3" label="已处理"></el-option>
            <el-option value="4" label="已撤销"></el-option>
          </el-select>

        </el-form-item>
        <el-form-item >
          <el-button type="primary" size="mini" icon="el-icon-search" @click="getData">搜索</el-button>
          <el-button size="mini" icon="el-icon-refresh" @click="reset">重置</el-button>
        </el-form-item>
        
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-button type="primary" size="mini" icon="el-icon-plus" @click="add">创建维修申请</el-button>
      </el-row>

        <el-table :data="tableData" style="width: 100%" v-loading="loading">
          <el-table-column prop="applyNo" align="center" label="编号" :show-overflow-tooltip="true" width="180">
            <template slot-scope="scope">
              <el-link type="primary"  @click="jump(scope.row)">{{scope.row.applyNo}}</el-link>
            </template>
          </el-table-column>
          <el-table-column prop="articleName" align="center" label="物品名称" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="location" align="center" label="物品位置" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column label="维修状态" align="center" prop="applyStatus">
            <template slot-scope="scope">
              <el-row>
                <el-tag v-if="scope.row.applyStatus == 0" type="info">草稿</el-tag >
                <el-tag v-if="scope.row.applyStatus == 1" type="primary">待审批</el-tag>
                <el-tag v-if="scope.row.applyStatus == 2" type="danger">审批驳回</el-tag>
                <el-tag v-if="scope.row.applyStatus == 3" type="success">已处理</el-tag>
                <el-tag v-if="scope.row.applyStatus == 4" type="danger">已撤销</el-tag>
              </el-row>
            </template>
          </el-table-column>

          <el-table-column prop="damageTime" align="center" label="物品损坏时间" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="currApprovedBy" align="center" label="当前审批人" :show-overflow-tooltip="true"> </el-table-column>
          <el-table-column prop="createTime" align="center" label="提交时间" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              {{parseTime(scope.row.createTime)}}
            </template>
          </el-table-column>
          <el-table-column width="60" align="center" label="操作">
            <template slot-scope="scope">
              <el-button @click="handleClick(scope.row)" v-if="scope.row.applyStatus == 1" size="mini" circle type="warning" icon="el-icon-refresh-left"></el-button>
              
            </template>
          </el-table-column>
        </el-table>

      
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getData"
      />


    <template>
      <el-dialog class="addNew"  title="创建维修申请" :visible.sync="dialogFormVisible" >
        <el-form :model="form" ref="form" label-width="130px" :rules="rules">
          <el-row>
            <el-col :span="12">
              <el-form-item label="物品名称:" prop="articleName"  >
                <el-input v-model="form.articleName" :disabled="isView"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="物品位置:" prop="location"  >
                <el-input v-model="form.location" :disabled="isView"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <!-- 归属部门 -->
              <el-form-item label="物品归属部门:" >
                <treeselect :disabled="isView"
                  v-model="form.ascriptionDept"
                  :options="options"
                  placeholder=""
                  empty-text=""
                  style="width: 100%"
                  @select="selectDepart"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="损坏日期:" >
                  <el-date-picker :disabled="isView"
                    style="width: 100%"
                    v-model="form.damageTime"
                    value-format="yyyy-MM-dd"
                    type="date"
                    placeholder="选择日期时间"
                  >
                  </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="描述:" :label-width="formLabelWidth">
            <el-input type="textarea" v-model="form.description" :disabled="isView"></el-input>
          </el-form-item>
          <el-form-item label="维修处理人" prop="ccUserList" v-show="!isView">
              <input type="hidden" v-model="form.currApprovedBy"/>
              <el-tag v-for="item in ccUserList" :key="item.id" style="margin-left: 3px;">{{item.userName}}</el-tag>
              <el-button type="info" plain size="mini"  icon="el-icon-plus" @click="handleUser">选择人员</el-button>
              <el-button type="info" plain size="mini" icon="el-icon-delete" @click="clearUser" v-if="ccUserList.length>0">清空人员</el-button>
            </el-form-item>
          <el-form-item label="物品损坏图片:" prop="fileList" :label-width="formLabelWidth" >
            <el-upload
              v-if="!isView"
              :action="updataUrl"
              list-type="picture-card"
              :file-list="form.fileList"
              :on-success="handleSuccess"
              :on-error="handleError"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <div v-if="isView">
              <el-image 
                v-for="item in form.fileList" :key="item.name" 
                style="width: 100px; height: 100px"
                :src="item.url"
                :preview-src-list="[item.url]"></el-image>
            </div>
            
          </el-form-item>
        </el-form>
        <div v-if="isView">
          <approvalHistory :processId="form.processId" v-if="form.processId && dialogFormVisible"></approvalHistory>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">关 闭</el-button>
          <el-button type="primary" v-if="!isView" :loading="submitLoading" @click="submitForm('form')" >确 定</el-button>
        </div>
      </el-dialog>

    </template>

    <el-dialog :visible.sync="dialogVisibleUser" title="选择人员">
      <deptUser @getTaskUser="getCCuser" :multiple="false" v-if="dialogVisibleUser"></deptUser>
    </el-dialog>
  </div>
</template>
<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import {
  getList,
  getRepairOrder,
  getDetail,
  delRepairOrder,
} from "@/api/workflow/itemRepair";
import { treeselectAll } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import deptUser from '../../components/userSelect/deptUser.vue'
import approvalHistory from '../../components/workflow/approvalHistory'
export default {
  // import引入的组件需要注入到对象中才能使用
  components: { Treeselect,deptUser,approvalHistory },

  data() {
    //自定义校验
    var checkImage = (rule, value, callback) => {
      if (!value || value.length < 1) {
        callback(new Error("图片不能为空！"));
      } else {
        callback();
      }
    };
    var checkApproved = (rule, value, callback) => {
      console.log(value)
      if (!this.ccUserList || this.ccUserList.length < 1) {
        callback(new Error("请选择维修人处理人！"));
      } else {
        callback();
      }
    };
    // 这里存放数据
    return {
      submitLoading:false,
      loading:false,
      isView:false,
      dialogVisibleUser:false,
      options:[],
      total: 0,
      forms: [],
      url: process.env.VUE_APP_BASE_API + "/school/file/",
      //viewimage
      // url: process.env.VUE_APP_BASE_API + "/school/file/"+this.form.articleImage[0],
      //res.data.articleImage[0]
      lookRepairOrder: false,
      queryParams:{
        pageSize:10,
        pageNum:1
      },
      //查询
      list: {
        articleName: "", //物品名称
        location: "", //物品所在位置
        applyStatus: "", //申请单状态 0-草稿 1-处理中 2-撤回 3-退回 4-办结
      },
      form: {
        articleName: "", //物品名称
        location: "", //物品所在位置
        applyStatus: "", //申请单状态 0-草稿 1-处理中 2-撤回 3-退回 4-办结
        ascriptionDept: "", //归属部门
        damageTime: "", //损坏时间
        description: "", //描述
        fileList: [], //保存图片
        articleImage:[],//提交后返回的图片
      },
      //上传图片
      dialogVisible: false,
      currentPage4: 4,
      dialogFormVisible: false,
      updataUrl: process.env.VUE_APP_BASE_API + "/test/uploadImage",
      dataList: {
        pageNum: 1,
        pageSize: 10,
        // processId: "", //流程ID
      },
      rules: {
        ascriptionDept: [
          { required: true, message: "请输入归属部门！", trigger: "change" },
        ],

        location: [
          {
            required: true,
            message: "请选择损坏物品位置！",
            trigger: "change",
          },
        ],

        articleName: [
          {
            required: true,
            message: "请选择损坏物品名称！",
            trigger: "change",
          },
        ],

        fileList: [
          { required: true, validator: checkImage, trigger: "change" },
        ],
        ccUserList:[{ required: true, validator: checkApproved, trigger: "change" },]
      },
      formLabelWidth: "120px",
      tableData: [],
      ccUserList:[]
    };
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合 42432
  methods: {
    handleUser(){
      this.dialogVisibleUser = true
    },
    clearUser(){
      this.ccUserList=[]
      this.form.currApprovedBy=null
    },
    getCCuser(data,isClose){
      this.ccUserList = data
      if(data){
        let ccUser = []
        for(let i=0;i<data.length;i++){
          ccUser.push(data[i].userName)
        }
        this.form.currApprovedBy = ccUser.join(',')
      }
      this.$refs['form'].clearValidate('ccUserList')
      this.dialogVisibleUser = isClose
    },
    getTreeselect(){
      treeselectAll().then(resp=>{
        this.options = resp.data
      })
    },
    //点击
    selectDepart(val) {
    },
    //分页查询信息
    getData() {
      this.loading = true
      getList(this.queryParams).then((res) => {
        this.tableData = res.data.list;
        this.total = res.data.total;
        this.loading = false
      });
    },

    //打开新增维修弹框时清空弹框数据
    add() {
      (this.form.articleName = ""),
      (this.form.location = ""),
      (this.form.ascriptionDept = null),
      (this.form.damageTime = ""),
      (this.form.applyStatus = 1),
      (this.form.description = ""),
      (this.form.fileList = []),
      this.dialogFormVisible = true;
      this.isView = false
      this.getTreeselect();
      this.$nextTick(() => {
        this.$refs["form"].clearValidate(); //打开弹框时清空弹框内所有校验红字提示
      });
     
    },
    //上传失败
    handleError() {},
    //上传成功钩子
    handleSuccess(resp, file, filelist) {
      if (!this.form.fileList) {
        this.form.fileList = [];
      }
      this.form.fileList.push(file);
      //清除上传图片的校验红字提示
      this.$refs.form.clearValidate("fileList"); 
      return true;
    },
    //删除维修单
    handleClick(row) {
      this.$confirm('确定要撤销维修申请吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delRepairOrder({ processInstanceId: row.processId }).then((resp) => {
            if ((resp.code = 200)) {
              this.$message({ message: "撤销成功", type: "success"});
              this.getData();
            } else {
              this.$message.error("删除维修单失败");
            }
          });
        })
      
      
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
    },
    //清空搜索框搜索条件
    reset() {
      this.queryParams={
        pageSize:10,
        pageNum:1
      }
      this.getData()
    },

    getpaer() {
      this.submitLoading = true
      getRepairOrder(this.form).then((res) => {
        if ((res.code = 200)) {
          this.$message({
            message: "新建维修单成功",
            type: "success",
          });
          this.submitLoading = false
          this.getData();
        } else {
          this.$message.error("新建维修单失败");
        }
        this.dialogFormVisible = false;
      });
     
    },
    //提交维修信息
    submitForm(formName) {
      console.log(this.form);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //处理图片
          
          this.form.articleImage = ''
          for(var i = 0; i<this.form.fileList.length; i++){ 
           this.form.articleImage += this.form.fileList[i].response.result
           this.form.articleImage += ","
               console.log(this.form.articleImage,"上传的图片")
           }

          this.getpaer();
        } else {
          return false;
        }
      });
    },
    getsrf() {},
    //查看维修单处理
    jump(row) {
      this.getTreeselect();
      this.dialogFormVisible = true;
      this.form = row
      let files =[]
      if(row.articleImage){
        const images =  row.articleImage.split(',')
        console.log(images)
        for(let i=0;i<images.length;i++){
          if(images[i]){
            files.push({
              name:images[i],
              url: this.url+images[i]
            })
          }
        }
        
      }
      this.form.fileList= files
      this.isView = true
    },
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getData();
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    //初始化页面数据
    
  },
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {}, // 如果页面有keep-alive缓存功能，这个函数会触发
};
</script>


